<template>
  <lay-layout class="example">
    <lay-header>
      <Navigationbar/>
    </lay-header>
    <lay-body>
      <div id="order-page" class="layui-container">
        <!-- 收货地址 -->
        <div class="address-section layui-card">
          <div class="layui-card-header">输入收货地址</div>
          <div class="layui-card-body">
            <div class="address-list">
              <div
                  v-for="(address, index) in addresses"
                  :key="index"
                  class="layui-card address-item"
                  :class="{ active: index === selectedAddress }"
                  @click="selectAddress(index)"
              >
                <p class="address-detail">{{ address.street }}</p>
                <p class="address-contact">{{ address.name }} {{ address.phone }}</p>
              </div>
            </div>
            <button class="layui-btn layui-btn-sm layui-btn-primary buttlan" @click="manageAddress">
              管理地址
            </button>
          </div>
        </div>

        <!-- 订单信息 -->
        <div class="order-section layui-card">
          <div class="layui-card-header">输入订单信息</div>
          <div class="layui-card-body">
            <table class="layui-table">
              <thead>
              <tr>
                <th>店铺宝贝</th>
                <th>商品属性</th>
                <th>原价</th>
                <th>数量</th>
                <th>小计</th>
              </tr>
              </thead>
              <tbody>
              <tr>
                <td>
                  <div class="product-infocc">
                    <img :src="'/'+order.product.image" alt="商品图片" />
                    <span class="product-name">{{ order.product.name }}</span>
                  </div>
                </td>
                <td>{{ order.product.attribute }}</td>
                <td>¥{{ order.product.price }}</td>
                <td>
                  <div class="layui-input-inline quantity-input">
                    <input
                        type="number"
                        v-model="order.quantity"
                        class="layui-input"
                        min="1"
                    />
                  </div>
                </td>
                <td>¥{{ (order.product.price * order.quantity).toFixed(2) }}</td>
              </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- 支付信息 -->
        <div class="payment-section layui-card">
          <div class="layui-card-header">支付详情</div>
          <div class="layui-card-body">
            <div class="total">
              <span>商品总价：</span>
              <span class="total-price">¥{{ (order.product.price * order.quantity).toFixed(2) }}</span>
            </div>

            <!-- 支付方式选择 -->
            <div class="payment-method" style="margin-top: 20px;margin-bottom: 20px">
              <label>选择支付方式：</label>
              <lay-select v-model="selectedPaymentMethod" placeholder="选择支付方式">
                <lay-select-option :value="1" label="支付宝"></lay-select-option>
                <lay-select-option :value="2" label="信用卡"></lay-select-option>
                <lay-select-option :value="3" label="微信支付"></lay-select-option>
              </lay-select>
              <p>当前选择的支付方式：{{ selectedPaymentMethodText }}</p>
            </div>

            <!-- 订单备注 -->
            <div class="order-remark" style="margin-top: 20px;margin-bottom: 20px">
              <label>订单备注：</label>
              <lay-textarea placeholder="请输入描述" v-model="order.remark">
              </lay-textarea>
            </div>

            <button class="layui-btn layui-btn-normal"
                    @click="submitOrder"
                    :disabled="isSubmitting"
                    style="margin-top: 20px;margin-bottom: 20px"
            >
              提交订单
            </button>
            <button class="layui-btn layui-btn-danger" @click="cancelOrder" style="margin-top: 20px;margin-bottom: 20px">
              取消订单
            </button>
          </div>
        </div>
      </div>

      <!-- 管理地址弹窗 -->
      <AddressManagement ref="addressManagement" />
    </lay-body>
  </lay-layout>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import Navigationbar from "@/components/homepage/Navigationbar/Navigationbar.vue";
import AddressManagement from "@/components/detailed/Orders/AddressManagement.vue";
import './orders.css';

const route = useRoute();
const router = useRouter();

const order = ref({
  product: {
    image: "",
    name: "",
    attribute: "",
    price: 0,
    merchantid: "", // 新增字段 merchantid
  },
  quantity: 1,
  remark: "",
});

const addresses = ref([]);
const selectedAddress = ref(0);
const isSubmitting = ref(false);
const selectedPaymentMethod = ref("1"); // 默认支付方式
let randomNumber = null;

// 支付方式的文本映射
const paymentMethods = {
  3: "信用卡",
  2: "微信支付",
  1: "支付宝"
};

// 计算当前选择的支付方式文本
const selectedPaymentMethodText = computed(() => paymentMethods[selectedPaymentMethod.value]);

// 计算商品总价
const totalPrice = computed(() => (order.value.product.price * order.value.quantity).toFixed(2));

onMounted(() => {
  // 获取路由参数中的 merchantid
  const { id, image, name, selectedColor, price, quantity, merchantid } = route.params;

  // 初始化订单数据
  order.value = {
    product: {
      id,
      image: image || "https://via.placeholder.com/50",
      name: name || "默认商品名称",
      attribute: selectedColor || "默认属性",
      price: price || 0,
      merchantid: merchantid || "", // 设置 merchantid
    },
    quantity: quantity || 1,
    remark: "",
  };

  console.log("初始化订单数据：", order.value);

  const user = JSON.parse(localStorage.getItem('user'));
  if (user) {
    axios.get('http://localhost:8080/adders/addresnt', {
      params: {
        userid: user.userid
      }
    })
        .then(response => {
          if (response.data.status === 200) {
            addresses.value = response.data.data;
            console.log("获取到的地址数据：", addresses.value);
          }
        })
        .catch(error => {
          console.error("获取地址数据失败:", error);
        });
  }
});

// 提交订单
async function submitOrder() {
  const user = JSON.parse(localStorage.getItem('user'));
  const userId = user.userid;

  if (isSubmitting.value) return;

  isSubmitting.value = true;

  const remark = order.value.remark.trim() === '' ? '默认备注内容' : order.value.remark;

  const orderData = {
    userid: userId,
    productid: order.value.product.id,
    parametername: order.value.product.attribute,
    totalprice: totalPrice.value,
    quantity: order.value.quantity,
    remark: remark,
    addressid: order.value.product.merchantid, // 使用 order 中的 addressid
  };

  console.log("提交的订单数据：", orderData);

  try {
    const response = await axios.get('http://localhost:8080/order/submit', { params: orderData });
    if (response.data.status === 200) {
      console.log("订单提交成功：", response.data);

      randomNumber = response.data.data;

      if (randomNumber) {
        window.open(`http://localhost:8080/alipay/pay?aliPay=${randomNumber}`);
      } else {
        console.error("randomNumber is not available");
      }
    } else {
      console.error("订单提交失败：", response.data.message);
    }
  } catch (error) {
    console.error("订单提交请求失败：", error);
  } finally {
    isSubmitting.value = false;
  }
}

// 取消订单
function cancelOrder() {
  const productId = route.params.id;
  const merchant = route.params.merchantid;
  console.log("订单已取消，返回商品页面");

  router.push({ name: 'Detailed', params: { id: productId, merchantid: merchant } });
}
</script>



